package cn.itcast.batch.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间处理工具类
 * 1）获取当前时间 yyyy-MM-dd HH:mm:ss
 * 2）获取当前日期 yyyyMMdd
 * 3)字符串日期转换：将yyyy-MM-dd HH:mm:ss,转换成date类型
 * 4）字符串日期转换，将yyyy-MM-dd HH:mm:ss,转换成"yyyyMMdd"
 */
public class DateUtil {

    private final static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
    private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");


    public static String timestampToDataStr(Long timestamp){
        Date date = new Date(timestamp);
        return new SimpleDateFormat(DateFormatDefine.DATE_TIME_FORMAT.getFormat()).format(date);
    }


    public static String getCurrentTime(){
        return new SimpleDateFormat(DateFormatDefine.DATE_TIME_FORMAT.getFormat()).format(new Date());
    }

    public static String getCurrentDate(){
        return new SimpleDateFormat(DateFormatDefine.DATE_FORMAT.getFormat()).format(new Date());
    }

    public static Date convertStringToDate(String dateStr){
        Date date = null;
        try {
            date = new SimpleDateFormat(DateFormatDefine.DATE_TIME_FORMAT.getFormat()).parse(dateStr);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static Date convertStringToDate2(String dateStr){
        Date date = null;
        try {
            date = new SimpleDateFormat(DateFormatDefine.DATE_FORMAT2.getFormat()).parse(dateStr);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }


    public static String convertStringToDateString(String timeStr){
        String dateStr = "";
        try {
            Date date = new SimpleDateFormat(DateFormatDefine.DATE_TIME_FORMAT.getFormat()).parse(timeStr);
            dateStr = new SimpleDateFormat(DateFormatDefine.DATE_FORMAT.getFormat()).format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return dateStr;
    }

    //获取当前日期 yyyy-MM-dd HH:mm:ss
    public static String getTodayDate(){
        return TIME_FORMAT.format(new Date());
    }

    /**
     * 获取本周一的时间：yyyyMMdd
     * @return
     */
    public static String getNowWeekStart(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);//周一
        //获取本周一日期
        return DATE_FORMAT.format(calendar.getTime());
    }

    //获取本月 yyyyMM
    public static String getYearMonthDate(){
        return getTodayDate().substring(0,7).replace("-","");
    }

    public static void main(String[] args) {
        System.out.println(getTodayDate());
    }

}
